<template>
  <div class="cardList">
    <div class="board">
      <div class="header flexBetween">
        <!--类型，状态选择，优惠券名称-->
        <div class="headerL flex">
          <el-select v-model="typeValue" class="typeSelect" placeholder="全部类型" style="width: 30%;">
            <el-option v-for="item in typeSelect" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="stateValue" class="stateSelect" placeholder="全部状态" style="width: 30%;">
            <el-option v-for="item in stateSelect" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-input v-model="cardName" placeholder="优惠券名称" style="width: 30%;" />
        </div>
        <!--查询，重置-->
        <div class="headerR flexBetween">
          <el-button type="primary" style="width: 45%;" class="find" @click="findCoupon">查询</el-button>
          <el-button style="width: 45%;" class="reSet" @click="reSet">重置</el-button>
        </div>
      </div>
      <!--新建，批量投放，删除-->
      <div class="header2 flex marginTop">
        <el-button type="primary" class="newAdd" @click="addCard">+新建</el-button>
        <el-button style="color: #A8ABB2;" @click="pushMoreShow = true" class="push">批量投放</el-button>
        <el-popconfirm width="340" confirm-button-text="确认删除" cancel-button-text="取消" :icon="InfoFilled"
          icon-color="#FFAD14" title="删除后商家将无法查看优惠券码的信息，且无法恢复，请谨慎操作！" @confirm="confirmEvents" @cancel="cancelEvent">
          <template #reference>
            <el-button class="delMore">批量删除</el-button>
          </template>
        </el-popconfirm>
      </div>
      <!--优惠券表格-->
      <table class="table marginTop">
        <thead>
          <th style="width: 3%;">
            <el-checkbox v-model="checked" size="large" />
          </th>
          <th style="width: calc(35% / 2)">优惠券名称</th>
          <th style="width: 10%;">状态</th>
          <th style="width: 10%">使用门槛</th>
          <th style="width: calc(35% / 3)">发放总量</th>
          <th style="width: calc(35% / 3)">已发放数</th>
          <th style="width: calc(35% / 3)">已使用数</th>
          <th style="width: 7%;">启用</th>
          <th style="width: calc(35% / 2)">操作</th>
        </thead>
        <tbody v-for="(item, index) in tableData">
          <tr>
            <td rowspan="2">
              <el-checkbox v-model="item.checked" size="large" />
            </td>
            <td colspan="7" style="height: 30px;">
              <div class="flexEvenly">
                <div class="type">
                  类型：
                  <label v-if="item.type === 0">代金券</label>
                  <label v-if="item.type === 1">折扣券</label>
                </div>
                <div class="type">
                  <label v-if="item.type === 0">抵扣金额：<label>{{ item.lessMoney }}</label> 元</label>
                  <label v-if="item.type === 1">折扣额度：<label>{{ item.discount }}</label> 折</label>
                </div>
                <div class="type">
                  有效时段：<label>{{ item.bteweenTime }}</label>
                </div>
              </div>
            </td>
            <td rowspan="2" style="padding: 0;">
              <!-- <div v-if="item.isSwitchOn === true"> -->
              <div>
                <div>
                  <el-button link type="primary" size="small" class="edit" :disabled="!item.isSwitchOn"
                    @click="editCard">编辑</el-button>
                  <el-button link type="primary" size="small" class="send" :disabled="!item.isSwitchOn"
                    @click="pushMoreShow = true">发放</el-button>
                </div>
                <div class="marginTop">
                  <el-button link type="primary" size="small" class="get" @click="cardGetList">领取列表</el-button>
                  <el-popconfirm width="340" confirm-button-text="确认删除" cancel-button-text="取消" :icon="InfoFilled"
                    icon-color="#FFAD14" title="删除后商家将无法查看优惠券码的信息，且无法恢复，请谨慎操作！" @confirm="confirmEvent(item.id)"
                    @cancel="cancelEvent">
                    <template #reference>
                      <el-button link type="primary" size="small" class="del">删除</el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </div>

            </td>
          </tr>
          <tr style="height: 50px;">
            <td>{{ item.name }}</td>
            <td>
              <label v-if="item.state === 1" style="color: #409eff;">未过期</label>
              <label v-if="item.state === 2" style="color:gray;">已过期</label>
            </td>
            <td>{{ item.howUse }}</td>
            <td>{{ item.allNum }}</td>
            <td>{{ item.sendNum }}</td>
            <td>{{ item.useNum }}</td>
            <td v-if="item.state === 1">
              <el-switch v-model="item.isSwitchOn" inline-prompt active-text="是" inactive-text="否"></el-switch>
            </td>
          </tr>
        </tbody>
      </table>
      <!--分页-->
      <div class="demo-pagination-block flexWC marginTop">
        <el-pagination v-model:current-page="post.pageNumber" v-model:page-size="post.pageSize"
          :page-sizes="[5, 10, 15, 20]" :small="small" :disabled="disabled" :background="background"
          layout="total, sizes, prev, pager, next, jumper" :total="400" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <!--批量投放Start-->
    <el-dialog v-model="pushMoreShow" title="选择会员">
      <template #default>
        <div class="VIPinfo">
          <div class="pushBody marginTop">
            <div class="chooseVIP flexBetween">
              <el-select v-model="sexValue" size="small" placeholder="全部">
                <el-option v-for="item in sexSelect" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>

              <div>
                <el-date-picker v-model="dateStart" type="date" size="small" placeholder="选择日期">
                </el-date-picker>--
                <el-date-picker v-model="dateEnd" type="date" size="small" placeholder="选择日期">
                </el-date-picker>
              </div>
              <el-button type="primary" size="small">查询</el-button>
            </div>
            <el-table ref="multipleTableRef" :data="VIPtableData" style="width: 100%"
              :cell-style="{ textAlign: 'center' }" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column label="会员卡号" width="120">
                <template #default="scope">{{ scope.row.cardID }}</template>
              </el-table-column>
              <el-table-column property="nickName" label="会员昵称" width="120" />
              <el-table-column property="name" label="姓名" width="120" />
              <el-table-column property="tel" label="手机号码" show-overflow-tooltip />
            </el-table>
            <!---->
            <div class="flexBetween marginTop" style="border-bottom: 1px solid #A8ABB2;">
              <div>
                <el-checkbox v-model="checked" size="large" />
                <label>全选 {{ VIPnum }} 条筛选结果</label>
              </div>
              <el-pagination small background layout="prev, pager, next" :total="50" class="mt-4" />
            </div>
            <!---->
            <div class="headerR flexBetween marginTop">
              <el-button @click="pushMoreShow = false">取消</el-button>
              <el-button type="primary" @click="pushMoreShow = false, putSubmit">确认</el-button>
            </div>
          </div>
        </div>
      </template>

    </el-dialog>
    <!--批量投放End-->
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { ElTable } from 'element-plus'
import router from '@/router';
import axios from 'axios';

//页码 
const post = ref({
  pageSize: 10,
  pageNumber: 1,
  pageSizeVIP: 5,
  pageNumberVIP: 1
})

//优惠券查询条件 Start ---------
const typeValue = ref(0)
const stateValue = ref(0)
//类型选择
const typeSelect = [
  {
    value: 0,
    label: '全部类型',
  },
  {
    value: 1,
    label: '代金券',
  },
  {
    value: 2,
    label: '折扣券',
  }
]
//状态选择
const stateSelect = [
  {
    value: 0,
    label: '全部状态',
  },
  {
    value: 1,
    label: '未过期',
  },
  {
    value: 2,
    label: '已过期',
  }
]
//输入优惠券名称
const cardName = ref('')

//优惠券查询条件End ---------------

//优惠券列表数据
const tableData = ref([
  //type:0-代金券   1-折扣券
  //state：state:0-全部；1-未使用（未过期）；2-已过期；3-已使用；4-已作废
  {
    id: 1,
    type: 0,
    lessMoney: 10.00,
    discount: 10,
    bteweenTime: '2019-04-10 ~ 2019-04-17',
    name: '10元优惠券',
    state: 1,
    howUse: 50.0,
    allNum: '无限制',
    sendNum: 11,
    useNum: 8,
    isSwitchOn: false,
    checked: false
  },
  {
    id: 2,
    type: 1,
    lessMoney: 10.00,
    discount: 9.8,
    bteweenTime: '2019-04-10 ~ 2019-04-17',
    name: '9.8折优惠券',
    state: 2,
    howUse: 50.00,
    allNum: 500,
    sendNum: 50,
    useNum: 13,
    isSwitchOn: false,
    checked: false
  },
  {
    id: 3,
    type: 0,
    lessMoney: 5.00,
    discount: 10,
    bteweenTime: '2019-04-10 ~ 2019-04-17',
    name: '5元优惠券',
    state: 1,
    howUse: 50.00,
    allNum: 1000,
    sendNum: 100,
    useNum: 20,
    isSwitchOn: false,
    checked: false
  }
])

//checked 选择框
const checked = ref(false)
watch(checked, (newVal, oldVal) => {
  tableData.value.forEach(element => {
    element.checked = newVal
  });
})

const small = ref(false)
const background = ref(false)
const disabled = ref(false)

//投放条件数据
const sexValue = ref('')
const sexSelect = [
  {
    value: 'allSex',
    label: '全部'
  },
  {
    value: 'man',
    label: '男'
  },
  {
    value: 'woman',
    label: '女'
  }
]
//投放会员生日选择
const dateStart = ref('')
const dateEnd = ref('')

//User用户表属性
interface User {
  cardID: string
  nickName: string
  name: string
  tel: string
}
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val
}
const VIPtableData: User[] = [
  {
    cardID: '40012341223',
    nickName: 'pigpig',
    name: 'Phoebe',
    tel: '18349349604',
  },
  {
    cardID: '40012341265',
    nickName: 'switch',
    name: 'Tom',
    tel: '18349349604',
  },
  {
    cardID: '40012341273',
    nickName: 'pigpig',
    name: 'Tom',
    tel: '18349349604',
  },
  {
    cardID: '40012341284',
    nickName: 'pigpig',
    name: 'Tom',
    tel: '18349349604',
  }
]
//User用户表数据总数
const VIPnum = ref(100)
//投放页面是否展示
const pushMoreShow = ref(false)
const pushMore = ref(false)



//接口1  Start
import type { coupon, findDto } from '@/api/YouHuiQuan/YouHuiQuan'
import { findCard, putCoupon, delCoupon, delCoupons } from '@/api/YouHuiQuan/YouHuiQuan'


//优惠券查询
const FindDto: findDto = reactive({
  type: String(typeValue.value),
  status: Boolean(stateValue.value),
  name: cardName.value,
  page: post.value.pageNumber,
  limit: post.value.pageSize,
})
//优惠券查询接口
// let cardList = async () => {
//   console.log(FindDto,1);
//   let { data }: { [propsName: string]: any } = await findCard(FindDto)


//   // if (data.code == 200) {
//   //   console.log(data);
//   //   tableData.value = data.data
//   // }
// }
onMounted(() => {
  cardList()
})

//发放优惠券（发放）
let putCard = async () => {
  let { data }: { [propsName: string]: any } = putCoupon({
    id: 1,
    limit: post.value.pageSizeVIP,
    name: cardName.value,
    page: post.value.pageNumberVIP,
    status: stateValue.value,
    uid: 1
  })
  if (data.code == 200) {
    console.log('发放优惠券');
    VIPtableData.values = data.data
  }
}

//删除接口，删除按钮
const confirmEvent = (id: number) => {
  console.log('confirm!')
  console.log('id', id);
  delCoupon({ id })
  ElMessage({
    showClose: true,
    message: '删除成功',
    type: 'success',
  })
}
const confirmEvents = () => {
  let ids = tableData.value.filter(item => item.checked).map(item => item.id)
  console.log(ids);
  delCoupons({ ids })
  ElMessage({
    showClose: true,
    message: '删除成功',
    type: 'success',
  })
}
const cancelEvent = () => {
  console.log('cancel!')
}
//接口 End


//接口2
function cardList() {
  axios({
    url: '/coupon/find',
    method: "get",
    params: {
      type: String(typeValue.value),
      status: Boolean(stateValue.value),
      name: cardName.value,
      page: post.value.pageNumber,
      limit: post.value.pageSize,
    }
  }).then((res) => {
    console.log(res);

  })
}
cardList();
//查询按钮
const findCoupon = () => {
  // FindDto.type=String(typeValue.value);
  console.log('type:', String(typeValue.value));
  console.log('status:', Boolean(stateValue.value));
  console.log('name:', cardName.value);
  console.log('page:', post.value.pageNumber);
  console.log('limit:', post.value.pageSize);
  console.log(FindDto)

  cardList()
}
//确认发放按钮
const putSubmit = () => {
  console.log(sexValue.value, dateStart.value, dateEnd.value);
  console.log('pageSizeVIP:',post.value.pageSizeVIP,'pageNumberVIP:', post.value.pageNumberVIP);
  putCard()
}
//新增/修改/列表/删除 按钮
const addCard = () => {
  router.push('/home/addcard')
}
const editCard = () => {
  console.log('aaaa');

  router.push('/home/addcard')
}
const cardGetList = () => {
  router.push('/home/cardgetlist')
}
//分页选择--一页数据条数--页码改变
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}


//重置
const reSet=()=>{
  typeValue.value=0;
  stateValue.value=0;
  cardName.value='';

}
</script>

<style scoped lang="less">
@import url('./YouHuiQuan.css');

div {
  box-sizing: border-box;
}

.cardList {
  width: 100%;
  height: 100%;
  font-size: 10px;
  position: relative;
  background-color: #F2F2F2;
  border-top: 1px #D5D5D5 solid;
  display: flex;
  flex-direction: column;
  justify-content: start;
  align-items: center;

  .board {
    width: 95%;
    height: 92%;
    padding: 30px 1.5%;
    background-color: white;
    margin-top: 30px;

    .header {
      width: 97%;

      .headerL {
        width: 60%;

        .typeSelect,
        .stateSelect {
          margin-right: 3%;
        }
      }

      .headerR {
        width: 10%;
        display: flex;
        flex-direction: row;
        justify-content: end;
      }
    }

    .table {
      width: 100%;
      text-align: center;
      border: 1px solid #D5D5D5;
      border-collapse: collapse;

      thead {
        font-size: 1em;
        background-color: #FAFAFA;
        border: none;
      }

      td {
        border: 1px solid #E8E8E8;
      }
    }
  }

  /* 批量投放pushMore */
  .pushMore {
    width: 100%;
    height: 100%;
    padding: 13%;
    position: absolute;
    top: -30px;
    left: 0;
    background-color: rgba(105, 104, 104, 0.482);
    margin-top: 30px;
    z-index: 3;

    .VIPinfo {
      padding: 15px;
      background-color: white;

      .pushHeader {
        padding-bottom: 20px;
        border-bottom: 1px solid #D5D5D5;

        .out:hover {
          cursor: pointer;
        }
      }

      .VIPtable {
        border-top: 1px solid #D5D5D5;
      }
    }
  }
}
</style>
